#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;

int p;

int qmi(int a, int k, int p)
{
    int res = 1 % p;
    while (k)
    {
        if (k & 1)
            res = (LL)res * a % p;
        k >>= 1;
        a = (LL)a * a % p;
    }
    return res;
}

LL c(int a, int b)
{
    // i : b, j : a
    // 注意b>a相当于是含0的情况，取模之后是0
    if (b > a)
        return 0;
    int res = 1;
    for (int i = 1, j = a; i <= b; ++i, --j)
    {
        res = (LL)res * j % p;
        res = (LL)res * qmi(i, p - 2, p) % p;
    }
    return res;
}

int Lucass(LL a, LL b)
{
    if (a < p && b < p)
        return c(a, b);
    else
        return c(a % p, b % p) * Lucass(a / p, b / p) % p;
}

int main()
{
    int n;
    cin >> n;
    while (n--)
    {
        LL a, b;
        cin >> a >> b >> p;
        cout << Lucass(a, b) << endl;
    }
    return 0;
}